/*
 * Copyright (c) 2019-2020, https://api.iot.10086.cn/(https://gitee.com/cmcc-iot-api/iot-card-open-application/).
 */
package cn.iot.card.open.tariff.service;

import cn.iot.card.open.constants.Constants;
import cn.iot.card.open.constants.ErrorCode;
import cn.iot.card.open.constants.UrlConstants;
import cn.iot.card.open.ec.dto.ResponseDto;
import cn.iot.card.open.modular.model.ResultDTO;
import cn.iot.card.open.modular.token.TokenService;
import cn.iot.card.open.pojo.page.LayuiPageFactory;
import cn.iot.card.open.pojo.page.LayuiPageInfo;
import cn.iot.card.open.tariff.dto.OfferingsDetailDTO;
import cn.iot.card.open.util.ApiRequestUtil;
import cn.iot.card.open.util.CommonUtil;
import cn.iot.card.open.util.JsonUtil;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资费信息业务操作
 *
 * @author 何光鑫
 * @date 20200221 10:39:44
 * @modify 20200221 何光鑫 v1.1.1 创建
 * @since v1.1.1
 */
@Service
@Slf4j
public class TariffChargesService {

    @Autowired
    private ApiRequestUtil apiRequestUtil;

    @Autowired
    private TokenService tokenService;

    /**
     * 调用api接口查询资费详情
     *
     * @param transId
     * @param accountId 集团id
     * @param offeringId 资费id
     * @return 返回 long
     * @throws IOException
     * @author 何光鑫
     * @date 20200221 11:30:59
     * @modify 20200221 何光鑫 v1.1.1 创建
     * @since v1.1.1
     */
    public LayuiPageInfo queryOfferingsDetail(String transId,String accountId ,String offeringId) throws IOException {
        Map<String, String> parameterMap = new HashMap<>();
        Page page = LayuiPageFactory.defaultPage();
        if (StringUtils.isBlank(accountId)) {
            log.warn("[{}] accountId is null.", transId);
            return LayuiPageFactory.createEmptyPageInfo();
        }
        //封装请求参数
        String url = UrlConstants.QUERY_OFFERINGS_DETAIL;
        parameterMap.put(Constants.REQUEST_PARAM_OFFERINGID, offeringId);
        // 调用api接口：先获取token，然后带着token调用api接口
        ResultDTO tokenResultDTO = doRequest(true, accountId, transId,parameterMap,url);
        // 如果此处响应失败即为获取token失败，返回失败原因
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            ErrorCode errorCode = ErrorCode.getByCode(tokenResultDTO.getCode());
            return LayuiPageFactory.cteateErrorMsg(errorCode);
        }
        // 获取token成功后解析api接口的响应结果
        String responseStr = tokenResultDTO.getMsg();
        String code = CommonUtil.getApiRspCode(responseStr);
        // 获取api接口的响应结果状态码，如果状态码为12021（token不存在或已过期），则重新获取token后再次调用api接口
        if (ErrorCode.ERR12021.getCode().equals(code)) {
            log.warn("[{}] token[accountId:{}] of offeringsDetail is invalid and start to get a new token.", transId, accountId);
            tokenResultDTO = doRequest(false, accountId, transId, parameterMap, url);
            // 如果此处响应失败即为获取token失败，返回失败原因
            if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
                ErrorCode errorCode = ErrorCode.getByCode(tokenResultDTO.getCode());
                return LayuiPageFactory.cteateErrorMsg(errorCode);
            }
            // 获取token成功后，重置responseStr（api接口的响应结果）
            responseStr = tokenResultDTO.getMsg();
        }
        log.info("[{}] query offeringsDetail result string is {}.", transId, responseStr);
        // 组装页面信息
        ResponseDto<OfferingsDetailDTO> result = JsonUtil.parseJson(responseStr, new TypeReference<ResponseDto<OfferingsDetailDTO>>() {});
        code = result.getStatus();
        if (!ErrorCode.SUCCESS.getCode().equals(code)) {
            // 如果api接口返回失败，则返回失败原因
            log.warn("[{}] query offeringsDetail error,error message is {}.", transId, result.getMessage());
            return LayuiPageFactory.cteateErrorMsg(ErrorCode.getByCode(code));
        }
        List<OfferingsDetailDTO> offeringsDetailLists = result.getResult();
        if (ToolUtil.isEmpty(offeringsDetailLists)) {
            log.warn("[{}] query offeringsDetail end,result is null.", transId);
            return LayuiPageFactory.createEmptyPageInfo();
        }

        page.setTotal(offeringsDetailLists.size());
        page.setRecords(offeringsDetailLists);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 封装参数
     *
     * @param tokenValid   true表示使用已经初始化了的token值，false表示使用重新生成的token值
     * @param accountId 集团id
     * @param transId
     * @param parameterMap 调用api接口的参数
     * @param url 调用API接口的请求路径
     * @return 返回 API接口响应结果（或者获取token失败的原因）
     * @throws IOException
     * @author 何光鑫
     * @date 20200108 17:29:12
     * @modify 20200108 何光鑫 v1.0 创建
     * @since v1.0
     */
    private ResultDTO doRequest(boolean tokenValid, String accountId, String transId,Map<String, String> parameterMap,String url) throws IOException {
        // 根据 accountId 查询 token
        ResultDTO tokenResultDTO = tokenService.getToken(tokenValid, accountId);
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            return tokenResultDTO;
        }
        parameterMap.put(Constants.REQUEST_PARAM_TOKEN, tokenResultDTO.getMsg());
        parameterMap.put(Constants.REQUEST_PARAM_TRANSID, transId);
        String methodUrl = apiRequestUtil.buildRequestUrl(parameterMap, url);
        log.info("[{}] request url is {}.", transId, methodUrl);

        tokenResultDTO.setMsg(apiRequestUtil.doGet(methodUrl));
        return tokenResultDTO;
    }
}
